package com.sptpc.learnspring.support;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import org.joda.money.CurrencyUnit;
import org.joda.money.Money;
import org.springframework.format.Formatter;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.util.Locale;

/**
 * 注意：
 * 1. 添加joda-money,hutool依赖
 * 2. 前端采用表单提交才能转换
 */
@Component
public class MoneyFormatter implements Formatter<Money> {

    @Override
    public Money parse(String s, Locale locale) throws ParseException {
        if (NumberUtil.isNumber(s)) {
            // 如果直接是数字，将其转化为Money类型
            return Money.of(CurrencyUnit.of("CNY"), NumberUtil.toBigDecimal(s));
        } else if (StrUtil.isNotEmpty(s)) {
            // 必须为"CNY 8.00"格式，才转化
            String[] split = StrUtil.split(s, " ");
            if (split!=null && split.length==2
                    && StrUtil.equalsAnyIgnoreCase("CNY", split[0])
                    && NumberUtil.isNumber(split[1])) {
                return Money.of(CurrencyUnit.of("CNY"), NumberUtil.toBigDecimal(split[1]));
            } else {
                throw new ParseException(s, 0);
            }
        }
        throw new ParseException(s, 0);
    }

    @Override
    public String print(Money money, Locale locale) {
        if (money == null) {
            return null;
        }
        return money.getCurrencyUnit().getCode() + " " + money.getAmount();
    }
}
